package main

import (
	"iot-base/common/cache"
	"iot-base/common/notify"
	"iot-base/devc/common/loader"
	"net"
	"strings"
	"sync"
	"time"

	"errors"
	"fmt"
)

func main() {
	loader.SetParam(false, "thermo", 30, GetTask)
	//loader.SetParam(false, "ups", 10, GetUPSTask)
	//loader.SetParam(false, "fire", 10, GetFireTask)
	wg := sync.WaitGroup{}
	wg.Add(1)
	wg.Wait()

}

func GetTask(id string, thing *cache.ThingInfo, v interface{}, round int64) (interface{}, error) {
	fmt.Println("in thermo", thing)
	ip := thing.GetThingParam("ip", "")
	if ip == "" {
		fmt.Println("ip is nil")
		return nil, errors.New("ip is nil")
	}
	port := thing.GetThingParam("port", "")
	if port == "" {
		fmt.Println("port is nil")
		return nil, errors.New("port is nil")
	}
	conn, err := net.DialTimeout("tcp", ip+":"+port, 3*time.Second)
	if err != nil {
		fmt.Println("connect " + ip + " err:" + err.Error())
		return nil, errors.New("connect " + ip + " err:" + err.Error())
	}
	now := time.Now().Unix()
	switch thing.Thing.ModelID {
	case "m_pm25":
		res, err := order("C", conn)
		if err != nil {
			return nil, err
		}
		fmt.Println("result:", res)
		fmt.Println("result:", strings.TrimSpace(res))
		notify.RawData(id, "pm", "", 0, strings.TrimSpace(res), now, now)
		res, err = order("JB", conn)
		if err != nil {
			return nil, err
		}
		fmt.Println("result:", res)
		fmt.Println("result:", strings.TrimSpace(res))
		notify.RawData(id, "ambient_temp", "", 0, strings.TrimSpace(res), now, now)
		res, err = order("JH", conn)
		if err != nil {
			return nil, err
		}
		fmt.Println("result:", res)
		fmt.Println("result:", strings.TrimSpace(res))
		notify.RawData(id, "apress", "", 0, strings.TrimSpace(res), now, now)
	case "m_pm10":
		res, err := order("C", conn)
		if err != nil {
			return nil, err
		}
		fmt.Println("result:", res)
		fmt.Println("result:", strings.TrimSpace(res))
		notify.RawData(id, "pm", "", 0, strings.TrimSpace(res), now, now)
		res, err = order("JB", conn)
		if err != nil {
			return nil, err
		}
		fmt.Println("result:", res)
		fmt.Println("result:", strings.TrimSpace(res))
		notify.RawData(id, "ambient_temp", "", 0, strings.TrimSpace(res), now, now)
		res, err = order("JH", conn)
		if err != nil {
			return nil, err
		}
		fmt.Println("result:", res)
		fmt.Println("result:", strings.TrimSpace(res))
		notify.RawData(id, "apress", "", 0, strings.TrimSpace(res), now, now)
	default:
		return nil, nil
	}
	return nil, nil
}

func order(order string, conn net.Conn) (string, error) {
	_, err := conn.Write([]byte(order + string(0x0D) + string(0x0A)))
	if err != nil {
		fmt.Println("conn write err:" + err.Error())
		return "", errors.New("conn write err!")
	}
	res := make([]byte, 1024)
	n, err := conn.Read(res)
	fmt.Println("n:", n)
	fmt.Println("res:", res[:n])
	if err != nil || n == 0 {
		fmt.Println("conn read err" + err.Error())
		return "", errors.New("conn read err" + err.Error())
	}
	return string(res[:n]), nil
}
